package com.itkf.core.configCenter.example;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.itkf.core.config.ConfigCenter;
import com.itkf.core.config.DtpProperties;
import com.itkf.core.configCenter.ConfigCenterService;
import com.itkf.core.configCenter.ConfigChangeListener;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

@Slf4j
@Component
@ConditionalOnProperty(prefix = "spring.dynamic.tp", name = "config-type", havingValue = "nacos")
public class NacosConfigCenterService implements ConfigCenterService {

    /**
     * 配置文件注入
     */
    private final DtpProperties dtpProperties;
    /**
     * nacos自带配置中心
     */
    private ConfigService configService;

    public NacosConfigCenterService(DtpProperties dtpProperties) {
        this.dtpProperties = dtpProperties;
    }

    @Override
    public void init() {
        try {
            ConfigCenter.Nacos nacosConfig = dtpProperties.getConfigCenter().getNacos();
            configService = NacosFactory.createConfigService(nacosConfig.getServerAddr());
        } catch (NacosException e) {
            throw new RuntimeException("Nacos client init failed", e);
        }
    }

    @Override
    public void subscribe(ConfigChangeListener listener) {
        ConfigCenter.Nacos nacosConfig = dtpProperties.getConfigCenter().getNacos();
        String dataId = nacosConfig.getDataId();
        String group = nacosConfig.getGroup();

        try {
            // 初始获取配置
            String initialConfig = configService.getConfig(dataId, group, 5000);
            listener.onChange(initialConfig);

            // 添加监听器
            configService.addListener(dataId, group, new Listener() {
                @Override
                public void receiveConfigInfo(String configInfo) {
                    listener.onChange(configInfo);
                }

                @Override
                public Executor getExecutor() {
                    return Executors.newSingleThreadExecutor();
                }
            });
        } catch (NacosException e) {
            log.error("Nacos subscribe config failed", e);
        }
    }

    @Override
    public void close() throws NacosException {
        if (configService != null) {
            configService.shutDown();
        }
    }
}
